package com.example.api.mall.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.IdUtil;
import com.example.api.mall.utils.RedisUtil;
import com.example.common.core.annotation.NoLoginAuth;
import com.example.common.core.constant.CachePreConstant;
import com.example.common.core.result.Result;
import com.example.entity.api.mall.capture.CaptchaVo;
import com.example.entity.api.mall.capture.VerifyVo;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 验证码
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    /**
     * 生成验证
     * @return
     */
    @GetMapping("/captcha")
    @NoLoginAuth
    public Result<CaptchaVo> captcha(){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 10);
        CaptchaVo captchaVo = new CaptchaVo();
        captchaVo.setKey(IdUtil.fastSimpleUUID());
        captchaVo.setImgBase64("data:image/png;base64," + lineCaptcha.getImageBase64());//放在img标签中直接显示
        RedisUtil.set(CachePreConstant.CAPTCHA_PREFIX + captchaVo.getKey(), lineCaptcha.getCode(), 300);
        return Result.success(captchaVo);
    }

    /**
     * 验证验证码
     * @return
     */
    @PostMapping("/verify")
    @NoLoginAuth
    public Result verify(@Validated @RequestBody VerifyVo verifyVo){
        String code = RedisUtil.get(CachePreConstant.CAPTCHA_PREFIX + verifyVo.getKey());
        if (verifyVo.getCode().equals(code)){
            return Result.success();
        }
        return Result.failure("验证码验证失败!");
    }

}
